package cacco.jp.mld;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cacco.jp.mld.panel.entity.UserEntity;
import cacco.jp.mld.panel.form.JqgridResponse;
import cacco.jp.mld.panel.form.StatusResponse;
import cacco.jp.mld.panel.service.UserService;
import cacco.jp.mld.panel.util.StringUtil;

@Controller
@RequestMapping(value = "/users")
public class UserController {

	private static final Logger logger = LoggerFactory
			.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String listHome(ModelMap map, HttpServletRequest request) {
		map.addAttribute("employee", new UserEntity());
		map.addAttribute("list_url", userService.getAll());
		UserEntity entity = (UserEntity) request.getSession()
				.getAttribute("aa");
		map.addAttribute("session", entity);
		System.out.println(entity);

		return "user/users";
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String listUser(ModelMap map, HttpServletRequest request) {
		map.addAttribute("employee", new UserEntity());
		map.addAttribute("list_url", userService.getAll());
		UserEntity entity = (UserEntity) request.getSession()
				.getAttribute("aa");
		map.addAttribute("session", entity);
		System.out.println(entity);

		return "user/users";
	}

	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public JqgridResponse<UserEntity> listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order) {

		logger.info("Listing items for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing items for grid with sort: {}, order: {}", sortBy,
				order);

		List<UserEntity> list = null;
		list = userService.getAlByPage(rows, page, sortBy, order);
		JqgridResponse<UserEntity> response = new JqgridResponse<UserEntity>();
		int totalRecords = userService.getTotalRecords();
		int total = totalRecords % rows == 0 ? (int) Math.ceil(totalRecords
				/ rows) : (int) Math.ceil(totalRecords / rows) + 1;

		logger.info("Listing users for grid with total rows {}", list.size());
		response.setRecords(list);
		response.setTotalRecords(totalRecords);
		response.setTotalPages(total);
		response.setCurrentPage(page);
		return response;
	}

	@RequestMapping(value = "/add", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	StatusResponse create(@RequestParam String userName,
			@RequestParam String password) {
		UserEntity user = new UserEntity(userName, password);
		StatusResponse response = new StatusResponse();
		if (userService.getUserByUserName(userName) == null) {
			userService.addUser(user);
			response.setSuccess(true);
			logger.info("Added new user: {}", user.getId());
		} else {
			response.setSuccess(false);
			response.setMessage("Username is exists");
			logger.info("Add user Failed");
		}
		return new StatusResponse(true);
	}

	@RequestMapping(value = "/update", method = RequestMethod.PUT)
	@ResponseBody
	public StatusResponse update(@RequestBody UserEntity user) {
		StatusResponse respone;
		user.setTimeUpDate(StringUtil.date2string(new Date()));
		try {
			userService.updateUser(user);
			respone = new StatusResponse(true);
			logger.info("Updated user: {}", user.getId());
		} catch (Exception e) {
			respone = new StatusResponse(false);
			respone.setMessage("Update failed");
			logger.info("User is not exists: {}", user.getId());
		}
		return respone;
	}

	@RequestMapping(value = "/delete", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	StatusResponse delete(@RequestParam Integer id) {
		StatusResponse response = new StatusResponse();
		try {
			userService.deleteUser(id);
			response.setSuccess(true);
			logger.info("Deleted user: {}", id);
		} catch (Exception e) {
			response.setSuccess(false);
			logger.info("Delete failed");
		}
		return response;
	}
}
